//
//  LSVideoScreenshotViewController.m
//  lightSpot
//
//  Created by lightSpot on 2024/1/1.
//  Copyright © 2024 lightSpot. All rights reserved.
//

#import "LSVideoScreenshotViewController.h"

#import "LSExtensionQueryButtonCell.h"

#import "LSVideoScreenshotEditViewController.h"

#import <TZImagePickerController/TZImagePickerController.h>

#import "LSVideoHandleManager.h"

#import "UIImage+Extension.h"

#import "WAVideoBox.h"

@interface LSVideoScreenshotViewController ()

@property (nonatomic , strong) WAVideoBox *videoBox;

@end

@implementation LSVideoScreenshotViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationBar.backgroundColor = [UIColor clearColor];
    [self setNavigationItemTitleViewWithTitle:@"视频截图"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"LSExtensionQueryButtonCell" bundle:nil] forCellReuseIdentifier:@"LSExtensionQueryButtonCell"];
    
    self.tableView.frame = CGRectMake(0,self.navigationBarHeight, kScreenWidth, kScreenHeight - self.navigationBarHeight);
    
    _videoBox = [WAVideoBox new];
}

#pragma mark - cellDataSource

- (NSArray *)cellDataSource {
    
    if (!self.dataSource) {
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:4];
        
        __block NSMutableArray *subarr = nil;
        __block NSDictionary *dict = nil;
                
        subarr = [NSMutableArray arrayWithCapacity:1];
        
        dict =  @{@"class":LSExtensionQueryButtonCell.class,
                  @"height":@([LSExtensionQueryButtonCell getCellFrame:[NSNumber numberWithFloat:400]]),
                  @"data":[LSExtensionQueryButtonCellModel ittemModelWithTitle:@"选择视频"],
                  @"delegate":@YES};
        [subarr addObject:dict];
                
        [arr addObject:subarr];

        self.dataSource = arr;
    }
    return self.dataSource;
}

#pragma mark ECextensionQueryButtonCellDelegate 选择视频

- (void)extensionQueryButtonCell:(LSExtensionQueryButtonCell *)cell button:(UIButton *)sender {
    [self gotoImagePickerController];
}

#pragma mark - goto

- (void)gotoImagePickerController {

    TZImagePickerController *vc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
    //视频
    vc.allowPickingImage = NO;
    vc.allowPickingVideo = YES;
    vc.allowPickingGif = NO;
    vc.allowTakeVideo = NO;
    vc.allowTakePicture = NO;
    @weakify(self);
    [vc setDidFinishPickingVideoHandle:^(UIImage *coverImage, PHAsset *asset) {
        @strongify(self);
        if (asset.mediaType == PHAssetMediaTypeVideo) {
            [SVProgressHUD show];
            //视频
            [LSVideoHandleManager requestAVAssetForVideo:asset complete:^(AVURLAsset *urlAsset) {
                NSString *duration = [self timeStr:asset.duration];
                
                [_videoBox clean];
                NSString *filePath = [self buildFilePath];
                __weak typeof(self) wself = self;
                
                [_videoBox appendVideoByPath:urlAsset.URL.absoluteString];
                [_videoBox rotateVideoByDegress:0];
                [_videoBox asyncFinishEditByFilePath:filePath complete:^(NSError *error) {
                    if (!error) {
                        [LSVideoHandleManager splitVideo:[NSURL fileURLWithPath:filePath] fps:1 splitCompleteBlock:^(BOOL success, NSMutableArray *splitimgs) {
                            //GCD
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [SVProgressHUD dismiss];
                                //视频截图
                                [wself gotoVideoScreenshotEditViewController:splitimgs duration:duration];
                            });
                        }];
                    }
                }];
            }];
        }
    }];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (NSString *)buildFilePath{
    return [NSTemporaryDirectory() stringByAppendingString:[NSString stringWithFormat:@"select-%f.mp4", [[NSDate date] timeIntervalSinceReferenceDate]]];
}

#pragma mark - goto

//视频截图
- (void)gotoVideoScreenshotEditViewController:(NSArray *)images duration:(NSString *)duration {
    LSVideoScreenshotEditViewController* vc = [LSVideoScreenshotEditViewController new];
    vc.images = images;
    vc.duration = duration;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSString *)timeStr:(int)s {
    int seconds = s % 60;
    int minutes = (s / 60) % 60;
    int hour = 0;
    if (minutes >= 60) {
        hour = minutes % 60;
    }
    if (hour > 0) {
        return [NSString stringWithFormat:@"%02d:%02d:%02d",hour,minutes, seconds];
    } else {
        return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
    }
}

@end
